<?php namespace Cms\Api;

use Cms\Model\Model as BaseModel;

class Model
{
	protected $db;
	
	protected $error = '未知错误';

	public function __construct()
	{
		$this->db = new BaseModel;
	}

	//获取所有模型
	public function getAll()
	{
		return Db::table('model')->orderBy("mid","asc")->get();
	}

	//添加模型
	public function store()
	{
		if($this->db->create())
		{
			if($this->db->add())
			{
				//创建数据表
				Db::execute('CREATE TABLE '.C('database.prefix').$_POST['table_name'].'(aid int) CHARSET UTF8');
				Db::execute('CREATE TABLE '.C('database.prefix').$_POST['table_name'].'_data(aid int,content text) CHARSET UTF8');
				return true;
			}
		}
	}

	//更新模型
	public function update()
	{
		if($this->db->create())
		{
			return $this->db->save();
		}
	}

	//删除模型
	public function destroy($id)
	{
		$model = $this->db->find($id);
		if($model['is_system']==1)
		{
			$this->error='系统模型不能删除';
			return false;
		}
		if($this->db->delete($id))
		{
			Db::execute("DROP TABLE ".C('database.prefix').$model['table_name']);
			Db::execute("DROP TABLE ".C('database.prefix').$model['table_name'].'_data');
			return true;
		}
	}

	//获取错误
	public function getError()
	{
		return $this->db->getError()?:$this->error();
	}
}